package jmind.core.image;

import java.io.File;

import jmind.base.util.DataUtil;
import jmind.base.util.FileUtil;

import org.im4java.core.ConvertCmd;
import org.im4java.core.IMOperation;

public class Image4Java {

    public static String imageMagickPath = "C:\\Program Files (x86)\\ImageMagick-6.7.3-Q16";
    public static boolean windows = System.getProperty("os.name").startsWith("Windows");

    public static void main(String[] args) {

        String src = "d:/data/2901.jpg";
        try {
            rotate(src, "d:/data/1.jpg", 270);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void testCompose() {
        String uploadDir = "D:/f/图片";
        String p = uploadDir + "/60";
        File[] sourcePic = new File(p).listFiles();
        String compose = Image4Java.compose(sourcePic, null, uploadDir);
        System.out.println(compose);
    }

    public static void testAddText() {
        String base = "D:/f/图片/";
        String srcPath = base + "chered2.jpg";
        String newPath = base + "new.jpg";

        try {
            Image4Java.addImgText(srcPath, newPath);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 旋转图片
     * @param src 原图
     * @param target  新图
     * @param angle 角度
    http://cping1982.blog.51cto.com/601635/130066
     * @throws Exception
     */
    public static boolean rotate(String src, String target, double angle) {
        IMOperation op = new IMOperation();
        op.addImage(src);//原图
        op.rotate(angle);
        op.addImage(target);//目标图
        final ConvertCmd convert = new ForWinConvertCmd();
        try {
            convert.run(op);
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将多张小图，合并到图格缩略图，并生成新地址。<br/>
     * 九宫格顺序依次是：<br/>
     * &nbsp; 1 2 3 <br/>
     * &nbsp; 4 5 6 <br/>
     * &nbsp; 7 8 9 <br/>
     * 
     * @param sourcePic
     *            待合并图片相对地址。<br/>
     *            最多只使用前九张已存在的小图。
     * @param markPic
     *            遮盖浮层，可以为空，默认用/board_thumb.jpg。
     * @return 返回自动生成的新九宫格图片相对地址。
     * @throws Exception
     *             异常抛出
     */
    public static String compose(final File[] sourcePic, String markPic, String uploadDir) {
        if (DataUtil.isEmpty(markPic)) {
            markPic = "/board_thumb.jpg";
        }
        final String targetPic = uploadDir + "/" + System.nanoTime() + ".jpg";
        final File file = new File(uploadDir + targetPic);
        FileUtil.makeDir(file);

        try {
            final IMOperation op = new IMOperation();
            op.size(190, 190);
            op.strip();
            op.addImage(uploadDir + markPic);
            int i = 0;
            for (int index = 0; index < sourcePic.length && i < 9; index++) {

                int x = i % 3;
                if (x == 1) {
                    x = 65;
                } else if (x == 2) {
                    x = 130;
                }
                int y = i / 3;
                if (y == 1) {
                    y = 65;
                } else if (y == 2) {
                    y = 130;
                }
                if (sourcePic[index].exists()) {
                    op.addImage(sourcePic[index].toString());
                    op.geometry(60, 60, x, y);
                    op.composite();
                    i++;
                } else {
                    System.err.println(sourcePic[index].getAbsolutePath() + " not exists.");
                }
            }
            //op.compose("Over");
            //op.sharpen(3D);

            //交错式输出
            op.interlace("plane");

            op.addImage(targetPic);//输出文件地址，需要放在所有参数后面

            final ConvertCmd convert = new ForWinConvertCmd();
            convert.run(op);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return targetPic;
    }

    /**
     * 根据坐标裁剪图片
     *
     * @param srcPath   要裁剪图片的路径
     * @param newPath   裁剪图片后的路径
     * @param x   起始横坐标
     * @param y   起始挫坐标
     * @param x1  结束横坐标
     * @param y1  结束挫坐标
     */
    public static void cutImage(String srcPath, String newPath, int x, int y, int x1, int y1) throws Exception {
        int width = x1 - x;
        int height = y1 - y;
        IMOperation op = new IMOperation();
        op.addImage(srcPath);

        /**
         * width：裁剪的宽度
         * height：裁剪的高度
         * x：裁剪的横坐标
         * y：裁剪的挫坐标
         */
        op.crop(width, height, x, y);

        op.addImage(newPath);

        ConvertCmd convert = new ConvertCmd();

        //linux下不要设置此值，不然会报错
        if (windows)
            convert.setSearchPath(imageMagickPath);
        convert.run(op);
    }

    /**
     * 根据尺寸缩放图片
     * @param width  缩放后的图片宽度
     * @param height  缩放后的图片高度
     * @param srcPath   源图片路径
     * @param newPath   缩放后图片的路径
     */
    public static void cutImage(int width, int height, String srcPath, String newPath) throws Exception {
        IMOperation op = new IMOperation();
        op.addImage(srcPath);

        op.resize(width, height);
        op.addImage(newPath);

        ConvertCmd convert = new ConvertCmd();

        //linux下不要设置此值，不然会报错
        if (windows)
            convert.setSearchPath(imageMagickPath);

        convert.run(op);
    }

    /**
     * 根据宽度缩放图片
     * @param width  缩放后的图片宽度
     * @param srcPath   源图片路径
     * @param newPath   缩放后图片的路径
     */
    public static void cutImage(int width, String srcPath, String newPath) throws Exception {
        IMOperation op = new IMOperation();
        op.addImage(srcPath);

        op.resize(width, null);
        op.addImage(newPath);

        ConvertCmd convert = new ConvertCmd();

        //linux下不要设置此值，不然会报错
        if (windows)
            convert.setSearchPath(imageMagickPath);

        convert.run(op);
    }

    /**
     * 给图片加水印
     * @param srcPath   源图片路径
     */
    public static void addImgText(String srcPath, String newPath) throws Exception {
        IMOperation op = new IMOperation();
        // 东南 southeast  西北 northwest

        op.font("宋体").gravity("northwest").pointsize(18).fill("red").draw("text 50,10 q.weibo.com");

        op.addImage();
        op.addImage();
        ConvertCmd convert = new ConvertCmd();

        if (windows)
            convert.setSearchPath(imageMagickPath);

        convert.run(op, srcPath, newPath);
    }

}
